package com.test.limit;

import cn.hutool.core.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * 计数限流
 *
 * @author zxs
 * @since 2020/06/23
 */
@Service("countLimit")
public class CountLimit implements Limiter {

    private static final String prefix = "CL:";

    @Autowired
    private ValueOperations<String, String> valueOperations;

    @Override
    public boolean isAllow(String key, Integer maxCount, Integer period) {
        String value = valueOperations.get(prefix + key);
        if (StrUtil.isEmpty(value)) {
            valueOperations.set(key, "1");
            return true;
        }
        Integer intValue = Integer.parseInt(value);
        if (intValue.compareTo(maxCount)>=0) {
            return false;
        }
        valueOperations.increment(key);
        return true;
    }
}
